<?php

namespace App\Service\Schedule;


use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Jobs\OpenShop\OrderAutoCloseDelayJob;
use App\Jobs\Schedule\ScheduleUserChangeLogJob;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\Common\HolidayModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\Schedule\ScheduleRemindSwitchModel;
use App\Models\Schedule\ScheduleRuleModel;
use App\Models\Schedule\ScheduleUserChangeLogModel;
use App\Models\Schedule\ScheduleUserModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\System\SystemNotifyService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class ScheduleService
{
    /**
     * 班次管理-列表
     * @param $shopId
     * @return array
     */
    public static function rulesList($shopId): array
    {
        return ScheduleRuleModel::query()
            ->whereIn('shopId', [$shopId, 0])
            ->orderByDesc('shopId')
            ->orderBy('start')
            ->orderByDesc('id')
            ->get()
            ->map(
                function ($ScheduleRuleModel) {
                    return [
                        "id"       => $ScheduleRuleModel->id,
                        "name"     => $ScheduleRuleModel->name,
                        "duration" => $ScheduleRuleModel->duration,
                        "start"    => date('H:i', strtotime($ScheduleRuleModel->start)),
                        "end"      => date('H:i', strtotime($ScheduleRuleModel->end)),
                        "color"    => $ScheduleRuleModel->color,
                    ];
                }
            )->toArray();
    }


    /**
     * 班次管理-编辑
     * @param $shopId
     * @param $userId
     * @param $id
     * @param $name
     * @param $start
     * @param $end
     * @param $color
     * @param $duration
     */
    public static function rulesUpdate($shopId, $userId, $id, $name, $start, $end, $color, $duration)
    {
        $total = ScheduleRuleModel::getCountByShopId($shopId, $name, $id);
        if ($total) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "班次名称已存在");
        }
        if ($id) {
            $scheduleRuleModel = ScheduleRuleModel::getInfoByShopId($shopId, $id);
            if (!$scheduleRuleModel) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
            }
            $beforeRuleModel = clone $scheduleRuleModel;
        } else {
            $scheduleRuleMaxTotal = Cache::remember(
                'tiger:openShop:schedule:maxTotal', getSwitchCacheTime(3600), function () {
                return ConfigModel::query()
                        ->where('module', 'schedule')
                        ->where('name', 'scheduleRuleMaxTotal')
                        ->value('value') ?? 10;
            }
            );

            $total = ScheduleRuleModel::getCountByShopId($shopId);
            if ($total >= $scheduleRuleMaxTotal) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "已达到最大班次了");
            }
            $scheduleRuleModel = new ScheduleRuleModel;
        }

        try {
            $start = date('H:i', strtotime($start));
            $end   = date('H:i', strtotime($end));

            $scheduleRuleModel->shopId   = $shopId;
            $scheduleRuleModel->name     = $name;
            $scheduleRuleModel->start    = $start;
            $scheduleRuleModel->end      = $end;
            $scheduleRuleModel->color    = $color;
            $scheduleRuleModel->duration = $duration;
            $scheduleRuleModel->save();
            if ($id) {

                $affectIds = ScheduleUserChangeLogJob::getAffectIds($shopId, $id);

                //修改原来使用过班次的记录
                ScheduleUserModel::query()
                    ->where('shopId', $shopId)
                    ->where('ruleId', $id)
                    ->update(
                        [
                            'ruleName'  => $name,
                            'ruleStart' => $start,
                            'ruleEnd'   => $end,
                            'color'     => $color,
                        ]
                    );

                // 添加修改记录
                dispatch(new ScheduleUserChangeLogJob($scheduleRuleModel->id, $shopId, $beforeRuleModel->toArray(), $affectIds));

            }
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "班次管理修改记录失败");
        }
    }

    /**
     * 班次管理-删除
     * @param $shopId
     * @param $id
     * @param $userId
     */
    public static function rulesDelete($shopId, $id, $userId)
    {
        $scheduleRuleModel = ScheduleRuleModel::getInfoByShopId($shopId, $id);
        if (!$scheduleRuleModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        $beforeRuleModel = clone $scheduleRuleModel;

        try {
            $scheduleRuleModel->isDeleted = 1;
            $scheduleRuleModel->save();

            $affectIds = ScheduleUserChangeLogJob::getAffectIds($shopId, $id);

            //删除原来使用过班次的记录
            ScheduleUserModel::query()
                ->where('shopId', $shopId)
                ->where('ruleId', $id)
                ->update(['isDeleted' => 1]);

            // 添加修改记录
            dispatch(new ScheduleUserChangeLogJob($scheduleRuleModel->id, $shopId, $beforeRuleModel->toArray(), $affectIds));

        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "班次管理删除记录失败");
        }
    }

    /**
     * 班次管理-提醒开关
     * @param $userId
     * @return array
     */
    public static function remindSwitch($userId): array
    {
        $switchData = ScheduleRemindSwitchModel::getSwitchData($userId);
        if ($switchData && count($switchData)) {
            $switchData = collect($switchData)->keyBy('type')->toArray();
        } else {
            $switchData = [];
        }
        $data = [];
        foreach (ScheduleRemindSwitchModel::TYPE_TEXT_MAPPING as $k => $v) {
            $type   = $switchData[$k]['type'] ?? $k;
            $data[] = [
                'id'       => $switchData[$k]['id'] ?? 0,
                'type'     => $type,
                'typeText' => ScheduleRemindSwitchModel::TYPE_TEXT_MAPPING[$type] ?? "",
                'switch'   => $switchData[$k]['switch'] ?? ScheduleRemindSwitchModel::SWITCH_ON,
            ];
        }
        return $data;
    }

    /**
     * 班次管理-提醒开关
     * @param $userId
     * @param $data
     */
    public static function remindSwitchUpdate($userId, $data)
    {
        $createData = [];
        $switchData = ScheduleRemindSwitchModel::getSwitchData($userId);
        if ($switchData && count($switchData)) {
            $switchData = collect($switchData)->keyBy('type')->toArray();
            foreach ($data as $v) {
                if (isset($switchData[$v['type']])) {
                    if ($switchData[$v['type']]['type'] == $v['type'] && $switchData[$v['type']]['switch'] != $v['switch']) {
                        ScheduleRemindSwitchModel::query()->where('id', $switchData[$v['type']]['id'])
                            ->update(['switch' => (int)$v['switch'], 'updatedByUid' => $userId]);
                    }
                } else {
                    if (in_array($v['type'], array_keys(ScheduleRemindSwitchModel::TYPE_TEXT_MAPPING))) {
                        $createData[] = [
                            'userId'       => $userId,
                            'type'         => $v['type'],
                            'switch'       => (int)$v['switch'],
                            'createdAt'    => time(),
                            'createdByUid' => $userId,
                        ];
                    }
                }
            }
        } else {
            foreach ($data as $v) {
                if (in_array($v['type'], array_keys(ScheduleRemindSwitchModel::TYPE_TEXT_MAPPING))) {
                    $createData[] = [
                        'userId'       => $userId,
                        'type'         => $v['type'],
                        'switch'       => (int)$v['switch'],
                        'createdAt'    => time(),
                        'createdByUid' => $userId,
                    ];
                }
            }
        }
        if ($createData) {
            ScheduleRemindSwitchModel::query()->insert($createData);
        }
    }

    /**
     * 班次管理-班次统计
     * @param int $shopId
     * @param $userId
     * @param string $startTime
     * @param string $endTime
     * @return array
     * @throws GuzzleException
     */
    public static function usersTotal(int $shopId, array $userId, string $startTime, string $endTime): array
    {
        $startDate = date('Ymd', strtotime($startTime));
        $endDate   = date('Ymd', strtotime($endTime));
        $scheduleUserModels = ScheduleUserModel::query()
            ->where('shopId', $shopId)
            ->when(
                $userId, function ($query) use ($userId) {
                $query->whereIn('userId', $userId);
            }
            )
            ->whereBetween('date', [$startDate,$endDate])
            ->get();

        // 第一行 - 所有店员
        $headers = self::scheduleStaff($shopId);

        // 第一列 - 班次
        $columns = ScheduleRuleModel::query()
                                    ->whereIn('shopId', [$shopId, 0])
                                    ->orderByDesc('shopId')
                                    ->orderBy('start')
                                    ->orderByDesc('id')
                                    ->get()
                                    ->map(function ($scheduleRuleModel) {
                                        return [
                                            'rel'   => (string)$scheduleRuleModel->id,
                                            'name'  => (string)$scheduleRuleModel->name,
                                            'start' => (string)date('H:i', strtotime($scheduleRuleModel->start)),
                                            'end'   => (string)date('H:i', strtotime($scheduleRuleModel->end)),
                                            'color' => $scheduleRuleModel->color,
                                        ];
                                    })->toArray();

        $lists = [];

        if ($scheduleUserModels->count()) {
            collect($scheduleUserModels)->each(
                function ($scheduleUserModel) use (&$lists) {

                    // 按照用户-班次聚合
                    $key = $scheduleUserModel->userId . '-' . $scheduleUserModel->ruleId;

                    // 第一次初始化坐标
                    if (!isset($lists[$key])) {
                        $lists[$key] = [
                            'headerRel' => (string)$scheduleUserModel->userId,
                            'columnRel' => (string)$scheduleUserModel->ruleId,
                            'count'     => 1,
                        ];
                        return;
                    }

                    // 数据存在
                    $lists[$key]['count'] += 1;
                }
            );
        }
        return [
            'headers' => $headers,
            'columns' => $columns,
            'lists'   => array_values($lists),
        ];
    }

    /**
     * 店长端 - 排班预览
     * @param int $shopId
     * @param array $userIds
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public static function scheduleOverviewManager(int $shopId, array $userIds, string $startTime, string $endTime): array
    {
        $startDate = date('Ymd', strtotime($startTime));
        $endDate   = date('Ymd', strtotime($endTime));

        // 店员userIds
        $staffIds = array_column(self::scheduleStaff($shopId), 'rel');
        $scheduleUserModels = ScheduleUserModel::query()
                                               ->whereBetween('date', [$startDate, $endDate])
                                               ->where('shopId', $shopId)
                                               ->whereIn('userId', $staffIds)
                                               ->when($userIds, function ($query) use ($userIds) {
                                                   $query->whereIn('userId', $userIds);
                                               })
                                               ->get();

        // 第一行 - 班次
        $headers = ScheduleRuleModel::query()
                                    ->whereIn('shopId', [$shopId, 0])
                                    ->orderByDesc('shopId')
                                    ->orderBy('start')
                                    ->orderByDesc('id')
                                    ->get()
                                    ->map(function ($scheduleRuleModel) {
                                        return [
                                            'rel'   => (string)$scheduleRuleModel->id,
                                            'name'  => (string)$scheduleRuleModel->name,
                                            'start' => (string)date('H:i', strtotime($scheduleRuleModel->start)),
                                            'end'   => (string)date('H:i', strtotime($scheduleRuleModel->end)),
                                        ];
                                    })->toArray();

        // 节假日
        $holidays = HolidayModel::query()->whereBetween('date', [$startDate, $endDate])->get()->keyBy('date')->toArray();

        // 第一列 - 日期
        $columns = [];
        while ($startDate <= $endDate) {

            $columns[] = [
                'rel'         => (string)$startDate,
                'date'        => (string)$startDate,
                'isHoliday'   => $holidays[$startDate]['isHoliday'] ?? 0,
                'holidayName' => mb_substr($holidays[$startDate]['name'] ?? '', 0, 2),
            ];

            $startDate = date('Ymd', strtotime($startDate . ' +1 day'));
        }

        $userIds   = $scheduleUserModels->pluck('userId')->unique()->values()->toArray();
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');

        // 数据
        $lists = [];
        $scheduleUserModels->map(function ($scheduleUserModel) use ($userInfos) {

            return [
                'columnRel' => $scheduleUserModel->date,
                'headerRel' => $scheduleUserModel->ruleId,
                'userId'    => $scheduleUserModel->userId,
                'userName'  => $userInfos[$scheduleUserModel->userId]['username'] ?? '',
                'uuid'      => $scheduleUserModel->date . '-' . $scheduleUserModel->ruleId,
            ];
        })->each(function ($item) use (&$lists) {

            // 按照同一天的班次聚合用户
            $uuid = $item['uuid'];

            // 第一次初始化坐标
            if (!isset($lists[$uuid])) {
                $lists[$uuid] = [
                    'columnRel' => (string)$item['columnRel'],
                    'headerRel' => (string)$item['headerRel'],
                ];
            }

            $lists[$uuid]['data'][] = [
                'userId'   => $item['userId'],
                'userName' => $item['userName'],
            ];
        });

        return [
            'headers' => $headers,
            'columns' => $columns,
            'lists'   => array_values($lists),
        ];
    }

    /**
     * 排班预览
     * @param $shopId
     * @param $startTime
     * @param $endTime
     */
    public static function scheduleEntrance(int $shopId, string $startTime, string $endTime)
    {
        $startDate = date('Ymd', strtotime($startTime));
        $endDate   = date('Ymd', strtotime($endTime));

        // 第一行 - 年月日
        $headers = [];
        $date    = $startDate;
        while ($date <= $endDate) {
            $headers[] = [
                'rel'  => (string)$date,
                'name' => (string)$date,
            ];
            $date = date('Ymd', strtotime($date) + 86400);
        }

        // 第一列 - 所有店员
        $columns = self::scheduleStaff($shopId);

        // 数据
        $lists = [];
        ScheduleUserModel::query()
                         ->whereBetween('date', [$startDate, $endDate])
                         ->where('shopId', $shopId)
                         ->get()
                         ->map(function ($scheduleUserModel) {
                             return [
                                 'columnRel' => (string)$scheduleUserModel->userId,
                                 'headerRel' => (string)$scheduleUserModel->date,
                                 'ruleId'    => (string)$scheduleUserModel->ruleId,
                                 'ruleName'  => (string)$scheduleUserModel->ruleName,
                                 'color'     => (string)$scheduleUserModel->color,
                                 'uuid'      => $scheduleUserModel->userId . '-' . $scheduleUserModel->date,
                             ];
                         })
                         ->each(function ($item) use (&$lists) {

                             // 按照同一天的用户聚合班次
                             $uuid = $item['uuid'];

                             // 第一次初始化坐标
                             if (!isset($lists[$uuid])) {
                                 $lists[$uuid] = [
                                     'columnRel' => (string)$item['columnRel'],
                                     'headerRel' => (string)$item['headerRel'],
                                 ];
                             }

                             $lists[$uuid]['data'][] = [
                                 'ruleId'   => $item['ruleId'],
                                 'ruleName' => $item['ruleName'],
                                 'color'    => $item['color'],
                             ];
                         });

        return [
            'headers' => $headers,
            'columns' => $columns,
            'lists'   => array_values($lists),
        ];
    }


    /**
     * 员工排班预览
     * @param int $shopId
     * @param $userId
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public static function preview(int $shopId, $userId, string $startTime, string $endTime): array
    {
        $startDate  = date('Ymd', strtotime($startTime));
        $endDate    = date('Ymd', strtotime($endTime));
        $dates      = self::getDates($startTime, $endTime);
        $originData = ScheduleUserModel::query()
            ->where('shopId', $shopId)
            ->where('userId', $userId)
            ->whereBetween('date', [$startDate, $endDate])
            ->get();
        if ($originData->count()) {
            collect($originData)->each(
                function ($scheduleUserModel) use (&$dates) {

                    // 日期存在
                    if (isset($dates[$scheduleUserModel->date])) {
                        $dates[$scheduleUserModel->date]['ruleData'][$scheduleUserModel->id] = [
                            'type'      => $scheduleUserModel->type,
                            'typeText'  => ScheduleUserModel::TYPE_TEXT[$scheduleUserModel->type] ?? "",
                            'ruleId'    => $scheduleUserModel->ruleId,
                            'ruleName'  => $scheduleUserModel->ruleName,
                            'ruleStart' => date('H:i', strtotime($scheduleUserModel->ruleStart)),
                            'ruleEnd'   => date('H:i', strtotime($scheduleUserModel->ruleEnd)),
                            'ruleColor' => $scheduleUserModel->color,
                        ];
                    }
                }
            );

            foreach ($dates as &$v) {
                $v['ruleData'] = isset($v['ruleData']) && is_array($v['ruleData']) ? array_values($v['ruleData']) : [];
            }
        }
        return array_values($dates);
    }

    /**
     * 获取两个时间的日期
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public static function getDates(string $startTime, string $endTime): array
    {
        $startDate = date('Ymd', strtotime($startTime));
        $endDate   = date('Ymd', strtotime($endTime));
        // 节假日
        $holidays = HolidayModel::query()->whereBetween('date', [$startDate, $endDate])->get()->keyBy('date')->toArray();
        $headers  = [];
        $date     = $startDate;
        while ($date <= $endDate) {
            $headers[$date] = [
                'rel'         => (string)$date,
                'name'        => (string)$date,
                'isHoliday'   => $holidays[$date]['isHoliday'] ?? 0,
                'holidayName' => mb_substr($holidays[$date]['name'] ?? '', 0, 2),
            ];
            $date      = date('Ymd', strtotime($date) + 86400);
        }
        return $headers;
    }

    /**
     * 排班修改提醒用户
     * @param string $startTime
     * @param string $endTime
     * @throws GuzzleException
     */
    public static function scheduleChangeRemind(string $startTime, string $endTime)
    {
        $data = [];
        ScheduleUserChangeLogModel::query()
            ->with(['scheduleRemindSwitchRel'])
            ->whereBetween('updatedAt', [strtotime($startTime), strtotime($endTime)])
            ->chunkById(
                100, function ($scheduleUserChangeLogModel) use (&$data) {
                foreach ($scheduleUserChangeLogModel as $v) {
                    $switch = ScheduleRemindSwitchModel::SWITCH_ON;
                    if ($v->scheduleRemindSwitchRel) {// 判断提醒开关状态
                        collect($v->scheduleRemindSwitchRel)->each(
                            function ($scheduleRemindSwitchModel) use (&$switch) {
                                if ($scheduleRemindSwitchModel->type == ScheduleRemindSwitchModel::TYPE_SCHEDULE) {
                                    $switch = $scheduleRemindSwitchModel->switch;
                                }
                            }
                        );
                    }
                    if ($switch == ScheduleRemindSwitchModel::SWITCH_ON) {
                        $data[$v->shopId . '-' . $v->userId] = [
                            'shopId'       => $v->shopId,
                            'userId'       => $v->userId,
                            'date'         => $v->date,
                            'updatedByUid' => $v->updatedByUid,
                        ];
                    }
                }
            }
            );

        if ($data) {
            //用户信息
            $userIds   = collect($data)->pluck('updatedByUid')->unique()->values()->toArray();
            $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');
            //门店信息
            $shopIds  = collect($data)->pluck('shopId')->unique()->values()->toArray();
            $shopInfo = collect((new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [])->keyBy('id');
            foreach ($data as $v) {
                $title = ($shopInfo[$v['shopId']]['shopCode'] ?? "") .
                    ($shopInfo[$v['shopId']]['name'] ?? "") .
                    ($userInfos[$v['updatedByUid']]['username'] ?? "") .
                    '为您设置新的排班，点击前往查看。';
                SystemNotifyService::customerBatchPush(
                    [$v['userId']],
                    $title,
                    "",
                    self::getSchedulePreviewUrl($v['date']),
                    $v['shopId'],
                    SystemNotifyCenterModel::NOTIFY_TYPE_3,
                    SystemNotifyCenterModel::NOTIFY_TARGET_2,
                    '',
                    SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
                    '',
                    SystemNotifyCenterModel::IS_POPUP_OFF,
                    1,
                    '创建消息',
                    ['path' => 'kuafoodmerchantapp://webView?url=' . self::getSchedulePreviewUrl($v['date'])]
                );
            }
        }
    }

    /**
     * 上班提醒
     * @param string $startTime
     * @param string $endTime
     */
    public static function scheduleStartWorkRemind(string $startTime, string $endTime){
        $data      = [];
        ScheduleUserModel::query()
            ->with(['scheduleRemindSwitchRel'])
            ->where('date', date('Ymd',strtotime($startTime)))
            ->whereBetween('ruleStart', [date('H:00:00', strtotime($startTime)), date('H:00:00', strtotime($endTime))])
            ->chunkById(
                100, function ($scheduleUserModel) use (&$data) {
                foreach ($scheduleUserModel as $v) {
                    $switch = ScheduleRemindSwitchModel::SWITCH_ON;
                    if ($v->scheduleRemindSwitchRel) {//判断提醒开关状态
                        collect($v->scheduleRemindSwitchRel)->each(
                            function ($scheduleRemindSwitchModel) use (&$switch) {
                                if ($scheduleRemindSwitchModel->type == ScheduleRemindSwitchModel::TYPE_WORK) {
                                    $switch = $scheduleRemindSwitchModel->switch;
                                }
                            }
                        );
                    }
                    if ($switch == ScheduleRemindSwitchModel::SWITCH_ON) {
                        $data[] = [
                            'shopId'    => $v->shopId,
                            'userId'    => $v->userId,
                            'date'      => $v->date,
                            'ruleName'  => $v->ruleName,
                            'ruleStart' => date('H:i', strtotime($v->ruleStart)),
                            'ruleEnd'   => date('H:i', strtotime($v->ruleEnd)),
                        ];
                    }
                }
            }
            );

        if ($data) {
            //门店信息
            $shopIds  = collect($data)->pluck('shopId')->unique()->values()->toArray();
            $shopInfo = collect((new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [])->keyBy('id');
            foreach ($data as $v) {
                $title = '您' .
                    ($shopInfo[$v['shopId']]['shopCode'] ?? "") .
                    ($shopInfo[$v['shopId']]['name'] ?? "") .
                    '的班次【' . $v['ruleName'] . '】，将于「' . date('Y-m-d', strtotime($v['date'])) . '」「' . $v['ruleStart'] . '」开始。';
                SystemNotifyService::customerBatchPush(
                    [$v['userId']],
                    $title,
                    "",
                    self::getSchedulePreviewUrl($v['date']),
                    $v['shopId'],
                    SystemNotifyCenterModel::NOTIFY_TYPE_3,
                    SystemNotifyCenterModel::NOTIFY_TARGET_2,
                    '',
                    SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
                    '',
                    SystemNotifyCenterModel::IS_POPUP_OFF,
                    1,
                    '创建消息',
                    ['path' => 'kuafoodmerchantapp://webView?url=' . self::getSchedulePreviewUrl($v['date'])]
                );
            }
        }
    }

    /**
     * 获取员工预览排班表url
     * @param string $date
     * @return string
     */
    public static function getSchedulePreviewUrl(string $date): string
    {
        $startTime = date('Y-m-01', strtotime($date));
        $endTime   = date('Y-m-t', strtotime($date));
        return config('webUrl.notify_web_cdn_url') . '#/pages/scheduling/preview/index?key=preview&startTime=' . $startTime . '&endTime=' . $endTime . '&hideAppBar=true';
    }

    /**
     * 员工列表
     * @param int $shopId
     * @return array
     * @throws GuzzleException
     */
    public static function scheduleStaff(int $shopId): array
    {
        return collect((new RmsShopApi())->getShopStaffListByShopId($shopId, false, true)['data']['list'] ?? [])
            ->map(function ($item) {
                return [
                    'rel'  => (string)$item['id'],
                    'name' => (string)$item['username'],
                ];
            })->toArray();
    }


    /**
     * 默认店铺班次数据
     * @return mixed
     */
    public static function getShopRuleConfig()
    {
        return Cache::remember(
            'tiger:schedule:shopRuleConfig', getSwitchCacheTime(86400), function () {
            return json_decode(
                ConfigModel::query()
                    ->where('module', 'schedule')
                    ->where('name', 'shopRuleConfig')
                    ->value('value') ?? '', true
            );
        }
        );
    }

    /**
     * 排班初始化店铺班次数据
     * @param int $shopId
     */
    public static function initShopScheduleRule(int $shopId = 0)
    {
        $shopRuleConfig = self::getShopRuleConfig();
        if (!$shopRuleConfig || !is_array($shopRuleConfig)) {
            return;
        }
        $time = time();

        // 新建门店初始化
        if ($shopId) {
            foreach ($shopRuleConfig as $v) {
                if ($v['name'] && $v['start'] && $v['end'] && $v['duration'] && $v['color']) {
                    ScheduleRuleModel::query()->firstOrCreate(
                        [
                            'shopId' => $shopId,
                            'name'   => $v['name'],
                        ],
                        [
                            'start'     => $v['start'],
                            'end'       => $v['end'],
                            'duration'  => $v['duration'],
                            'color'     => $v['color'],
                            'createdAt' => $time,
                        ]
                    );
                }
            }
        } else {

            // 历史门店数据初始化
            OpenShopSignOrderModel::query()
                ->with(['mainProcessRel'])
                ->whereIn('status', [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE])
                ->chunkById(
                    100, function ($openShopSignOrderModel) use ($time, $shopRuleConfig) {

                    foreach ($openShopSignOrderModel as $v) {
                        if ($v->mainProcessRel && $v->mainProcessRel->shopId) {
                            foreach ($shopRuleConfig as $rule) {
                                if ($rule['name'] && $rule['start'] && $rule['end'] && $rule['duration'] && $rule['color']) {
                                    ScheduleRuleModel::query()->firstOrCreate(
                                        [
                                            'shopId' => $v->mainProcessRel->shopId,
                                            'name'   => $rule['name'],
                                        ],
                                        [
                                            'start'     => $rule['start'],
                                            'end'       => $rule['end'],
                                            'duration'  => $rule['duration'],
                                            'color'     => $rule['color'],
                                            'createdAt' => $time,
                                        ]
                                    );
                                }
                            }
                        }
                    }
                }
                );
        }
    }

}
